package com.hjs.community.inform.job;


import com.community.common.core.corethreadPool.ExecutorUtils;
import com.hjs.community.inform.constant.RedisKey;
import com.hjs.community.inform.dto.SMSDto;
import com.hjs.community.inform.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Slf4j
public class SMSJob {

    @Autowired
    private SMSUtils smsUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/15 * * * * *")
    public void reSmsSend() {

        ExecutorUtils.getThreadPoll().submit(()->{
            //获取任务
            Set members = redisTemplate.opsForSet().members(RedisKey.SEND_SMS_ERROR_KEY);

            if (members.isEmpty()) {
                log.debug("任务为空，该定时任务结束");
                return;
            }
            while (true) {
                Iterator iterator = members.iterator();
                if (iterator.hasNext()) {
                    SMSDto smsDto = (SMSDto) iterator.next();
                    Boolean flag = smsUtils.query(smsDto.getTaskId(), smsDto.getMobile());
                    if (!flag) {
                        // 需要重新发送了
                        SMSDto newSMDeo = new SMSDto();
                        BeanUtils.copyProperties(smsDto, newSMDeo);
                        //smsUtils.send(newSMDeo);
                        log.debug("定时任务--重新发送");
                    }
                    // 这个短信已经发送成功了，需要删除
                    redisTemplate.opsForSet().remove(RedisKey.SEND_SMS_ERROR_KEY, smsDto);
                }
            }

        });

    }
}
